package com.atguigu.sparkstreaming.examples

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.{CanCommitOffsets, HasOffsetRanges, KafkaUtils, OffsetRange}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Created by Smexy on 2022/7/15
 *
 *
 */
object AtLeastOnceTransformTemplateDemo {

  def main(args: Array[String]): Unit = {

    val streamingContext = new StreamingContext("local[*]", "TransformDemo", Seconds(10))

    //所有的消费者参数都可以在 ConsumerConfig
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hadoop102:9092,hadoop103:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "2203092",
      "auto.offset.reset" -> "latest",
      // 第一步
      "enable.auto.commit" -> "false"
    )

    val topics = Array("topicA")

    val ds: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    //在Driver端声明偏移量
    var ranges: Array[OffsetRange] = null
    //第二步: 获取偏移量
    val ds1: DStream[ConsumerRecord[String, String]] = ds.transform(rdd => {

      ranges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges

      //可以转换，在后续转换
      rdd
    })

    // 第三步：各种转换

    //使用转换后的ds
    /*ds2.foreachRDD(rdd => {

      //输出到redis,mysql,es,hbase

      //手动提交offsets
      ds.asInstanceOf[CanCommitOffsets].commitAsync(ranges)

    })*/

    // 启动APP
    streamingContext.start()

    // 阻塞进程，让进程一直运行
    streamingContext.awaitTermination()

  }

}
